﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Data
{
    public class SqlProvider
    {
        #region
        public string ErrorMessage { get; set; }
        private SqlConnection _connection;
        private readonly string _connectionString;
        #endregion

        public SqlProvider()
        {
            ErrorMessage = string.Empty;
            try
            {
                if (_connectionString == null)
                {
                    _connectionString = ConfigurationManager.ConnectionStrings["ConnectionStrings"].ConnectionString;
                }
                if (_connection == null)
                {
                    _connection = new SqlConnection(_connectionString);
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                throw;
            }
        }

        public SqlConnection CreateConnection()
        {
            try
            {
                if (_connectionString != null && _connection != null)
                {
                    _connection = new SqlConnection(_connectionString);
                }

                if (_connection != null && _connection.State == ConnectionState.Closed)
                {
                    _connection.Open();
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
            }
            return _connection;
        }

        public void CloseConnection()
        {
            try
            {
                if (_connection.State == ConnectionState.Open)
                {
                    _connection.Close();
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
            }
        }

        public void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    if (_connection != null)
                    {
                        if (_connection.State == ConnectionState.Open)
                        {
                            _connection.Close();
                        }
                        _connection.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
            }
        }
    }
}
